/*
 * Copyright (C) 2013 AndXmppSDK Project <hljdrl@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drl.xmpp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.drl.xmpp.storage.table.VCardTable;
import org.drl.xmpp.util.BitmapHelper;
import org.drl.xmpp.util.StringHelper;
import org.drl.xmpp.util.StringUtils2;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.VCard;

import android.content.Context;

/**
 * @author hljdrl@gmail.com
 *
 */
public final class VCardTask extends Thread {

	private List<String> queue = new ArrayList<String>();
	private Context context;
	private boolean running = false;
	private TalkClient mTalk;
	private String PATH_AVATAR;
	private String mUserJIDKey;
	private VCardManager mVCardManager;
	private UserInfo user;
	public VCardTask(TalkClient talk,VCardManager vm) {
		mTalk = talk;
		mVCardManager = vm;
		PATH_AVATAR = "";
		user = talk.getUserInfo();
		mUserJIDKey = StringUtils2.parseName(user.getJid());
	}
	
	public synchronized void addToQueue(String jid) {
		synchronized (queue) {
			if (!queue.contains(jid)) {
				queue.add(jid);
			}
		}
		Thread.State state = getState();
		if(state == Thread.State.WAITING){
			notify();
		}

	}
	public void startQueue()
	{
		Thread.State state = getState();
		if(state == Thread.State.NEW){
			start();
		}
	}
	public synchronized void stopQueue()
	{
		running = false;
		Thread.State state = getState();
		if(state == Thread.State.WAITING){
			notify();
		}
	}
	public synchronized void addToQueueAsList(List<String> jids)
	{
		synchronized (queue) {
			if (jids != null && jids.size() > 0) {
				queue.addAll(jids);
			}
		}
		Thread.State state = getState();
		if(state == Thread.State.WAITING){
			notify();
		}
	}
	
	/**
	 * @see java.lang.Thread#run()
	 */
	@Override
	public synchronized void run() {
		running = true;
		while (running) {
			List<String> del = new ArrayList<String>();
			for(int i=0;i<queue.size();i++){
				String jid=queue.get(i);
				String hash = VCardTable.getInstance().finalVCardAvatorImageHash(jid);
				if(!StringHelper.isText(hash)){
				 reloadVCard(jid);
				}
				del.add(jid);
			}
			queue.removeAll(del);
			if(queue.size()==0 || queue==null || queue.size()<=0){
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void reloadAvatar(String jid){
		
	}

	
	public void reloadVCard(String jid) {
		jid = StringUtils.parseBareAddress(jid);
		VCard vcard = new VCard();
		try {
			vcard.setJabberId(jid);
			vcard.load(mTalk.getConnection(), jid);
			persistVCard(jid, vcard);
			vcard = null;
		} catch (XMPPException e) {
			e.printStackTrace();
			vcard.setJabberId(jid);
			try {
				vcard.load(mTalk.getConnection(), jid);
				persistVCard(jid, vcard);
				vcard = null;
				System.gc();
			} catch (XMPPException e1) {
				e1.printStackTrace();
			}
			System.gc();
		}
	}
	
	private void persistVCard(String jid, VCard vcard) {
		if (jid == null || android.text.TextUtils.isEmpty(jid.trim())
				|| vcard == null) {
			return;
		}
		byte[] bytes = vcard.getAvatar();
		if (bytes != null && bytes.length > 0) {
			vcard.setAvatar(bytes);
			try {
				String hash = vcard.getAvatarHash();
				
				String JIDName = StringUtils2.parseName(jid);
				if(mUserJIDKey.equals(JIDName)){
				bytes = BitmapHelper.getRoundedCornerBitmapToBytes(bytes, 20);
				}
				
				final File avatarFile = new File(PATH_AVATAR, hash);
				writeAvatarSync(bytes, avatarFile);
				VCardTable.getInstance().write(jid, String.valueOf(System.currentTimeMillis()), hash);
//				ContactDAO.onUpdataContactItemAsPhotoHash(context, jid, hash);
				
				mVCardManager.notifyVcardChanged(jid, hash);
			} catch (Exception e) {
			}
		}
	}
	
	public static final  void writeAvatarSync(byte buf[], File avatarFile)
			throws IOException {
//		if(HTalkClient.isSDCard()){
			FileOutputStream out = new FileOutputStream(avatarFile);
			out.write(buf, 0, buf.length);
			Thread.yield();
			out.close();
//		}
	}

}
